package com.niubility.controller;


import com.niubility.entity.College;
import com.niubility.entity.Department;
import com.niubility.entity.SearchMain;
import com.niubility.exception.CustomException;
import com.niubility.server.IArticleServer;
import com.niubility.server.IColService;
import com.niubility.server.IDepartmentService;
import com.niubility.server.IFollowServer;
import com.niubility.server.Impl.SearchServer;
import com.niubility.vo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/*
*@Author : GongGeng
*@FinishDate : 2018-01-27
*@Description : the class of department controller layer
*/

@Controller
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @Resource
    private SearchServer searchServer;

    @Resource
    private IColService collegeService;

    @Resource
    private IFollowServer followServer;

    @Resource
    private IArticleServer articleServer;

    Logger logger = Logger.getLogger("DepartmentController");

    //更新社团数据
    @RequestMapping("/updateDep")
    public void update(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        Department department=new Department();
        TrueFalse trueFalse=new TrueFalse();
        int depId = Integer.parseInt(req.getParameter("depId"));
        String depName = req.getParameter("depName");
        String depSign = req.getParameter("depSign");
        department.setDepId(depId);
        department.setDepMaster(Integer.parseInt(req.getParameter("depMaster")));
        department.setDepName(depName);
        department.setDepSign(depSign);
        department.setDepPicture(req.getParameter("depPicture"));
        department.setDepTel(req.getParameter("depTel"));

        SearchMain searchMain = new SearchMain();
        searchMain.setId(depId);
        searchMain.setName(depName);
        searchMain.setMaix(depSign);

        String result=null;
        try {
            //更新索引表的信息
            searchServer.Update(searchMain);
            trueFalse.setSuccess(departmentService.update(department));
            result = callback + "(" + JSONObject.fromObject(trueFalse);
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //通过账号加载社团数据
    @RequestMapping("/loadDepByAcount")
    public void loadDepByAcount(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        String depAcount=req.getParameter("depAcount");
        String result=null;
        try {
            Department department = departmentService.loadDepByAcount(depAcount);
            result = callback + "(" + JSONObject.fromObject(department).toString() + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //加载指定学校的社团信息
    @RequestMapping("/displayDepByColId")
    public void loadAll(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        int page= Integer.parseInt(req.getParameter("page"));
        int displayCounts=Integer.parseInt(req.getParameter("displayCounts"));
        String result=null;
        try {
            List<Department> departmentList = departmentService.loadAllInCol(Integer.parseInt(req.getParameter("colId")), Integer.parseInt(req.getParameter("page")), Integer.parseInt(req.getParameter("displayCounts")));
            String colName=collegeService.loadByColId(Integer.parseInt(req.getParameter("colId"))).getColName();
            ResultAndTag resultAndTag = new ResultAndTag();
            resultAndTag.setColName(colName);
            resultAndTag.setHasNext(true);
            if (departmentList.size() < displayCounts + 1) {
                resultAndTag.setHasNext(false);
            }
            if (departmentList.size() < displayCounts) {
                resultAndTag.setList(departmentList);
            } else {
                resultAndTag.setList(departmentList.subList(0, displayCounts));
            }
            result = callback + "(" + JSONObject.fromObject(resultAndTag).toString() + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //通过ID加载社团数据
    @RequestMapping("/loadDepById")
    public void loadDepById(HttpServletRequest req, HttpServletResponse resp) throws CustomException {
        int depId=0;
        String result=null;
        String callback=req.getParameter("callback");
        if(req.getParameter("depId")!=null) {
            depId = Integer.parseInt(req.getParameter("depId"));
        }else{
            try {
                depId= Integer.parseInt(req.getSession().getAttribute("userId").toString());
            }catch (Exception e){
                result = callback+"({"+"\"returncode\""+":"+103+"})";
                try {
                    resp.getWriter().write(result);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                throw new CustomException();
            }
        }


        //System.out.println(depId);
        try {
            Department department = departmentService.loadDepById(depId);
            int fansNum = followServer.FollowNumber(depId);
            int attentionNum=followServer.FollowDepNumber(depId);
            int artNum=articleServer.articleNum(depId);
            DepartmentVo departmentVo=new DepartmentVo();
            departmentVo.setDepId(depId);
            departmentVo.setDepName(department.getDepName());
            departmentVo.setDepPicture(department.getDepPicture());
            departmentVo.setDepSign(department.getDepSign());
            departmentVo.setFansNum(fansNum);
            departmentVo.setAttentionNum(attentionNum);
            departmentVo.setArtNum(artNum);
            result = callback + "(" + JSONObject.fromObject(departmentVo).toString() + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //删除社团
    @RequestMapping("/delDepByIds")
    public void delDepById(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        int depId= Integer.parseInt(req.getParameter("depId"));
        SearchMain searchMain = new SearchMain();
        String result = null;
        int colId=departmentService.loadDepById(depId).getDepCollege();
        try {

            searchMain.setId(depId);
            //向检索表添加检索信息
            searchServer.Delete(searchMain);
            TrueFalse trueFalse = new TrueFalse();
            trueFalse.setSuccess(departmentService.delDepById(depId)&collegeService.updateColDeps(colId,-1));
            result = callback + "(" + JSONObject.fromObject(trueFalse).toString() + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
